<?php


namespace app\exception;


use think\exception\Handle;

use think\facade\Log;
use think\Request;
use think\Response;
use Throwable;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;
    //需要返回客户端当前请求的URL路径

    /**
     * @param Request $request
     * @param Throwable      $e
     *
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {

       if($e instanceof BaseException){
           // 如果是用户操作问题 则不记录日志
          Log::close();
           //如果是自定义异常类
           $this->code = $e->code;
           $this->msg = $e->msg;
           $this->errorCode = $e->errorCode;
       } else{
           Log::clear();
           //在调试模式下  后端人员 想要获取的是 详细的错误信息
           if(env('APP_DEBUG')){
               return parent::render($request,$e);
           }else{
               //关闭系统设置的日志记录
               $this->code = 500;
               $this->msg = '服务器内部错误,无法告诉你';
               $this->errorCode = 999;
               //手动设置自己的日志记录
               $this->recodeErrorLog($e);
           }

       }

       $result = [
           'msg' => $this->msg,
           'error_code'=>$this->errorCode,
           'request_url'=>$request->url()
       ];
        return json($result,$this->code);
    }

    /**
     * @param Throwable $e
     */
    public function recodeErrorLog(Throwable $e){
          Log::record($e->getMessage(),'error');
    }
}